<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptid">
<!--        <el-input-->
<!--          v-model="queryParams.deptid"-->
<!--          placeholder="请输入部门id"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
        <el-tree-select
          v-model="queryParams.deptid"
          :data="deptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }"
          value-key="id"
          placeholder="请选择归属部门"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="系统" prop="busisystemid">
<!--        <el-input-->
<!--          v-model="queryParams.busisystemid"-->
<!--          placeholder="请输入系统id"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
        <el-select
          v-model="queryParams.busisystemid"
          placeholder="请选择系统"
        >
          <el-option
            v-for="item in systemList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            @keyup.enter="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="toolname">
        <el-input
          v-model="queryParams.toolname"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="描述" prop="memo">
        <el-input
          v-model="queryParams.memo"
          placeholder="请输入描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据库类型" prop="dbtype" label-width="120">
        <el-select v-model="queryParams.dbtype" placeholder="请选择数据库类型" clearable>
          <el-option
            v-for="dict in operation_db_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="sql内容" prop="sqlcontent">-->
<!--        <el-input-->
<!--          v-model="queryParams.sqlcontent"-->
<!--          placeholder="请输入sql内容"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-input
          v-model="queryParams.status"
          placeholder="请输入状态"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['operation:sqltool:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['operation:sqltool:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['operation:sqltool:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['operation:sqltool:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sqltoolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="部门" align="center" prop="deptname" width="120"/>
      <el-table-column label="系统" align="center" prop="busisystemname">
        <template #default="scope">
          <el-tag type="primary">{{scope.row.busisystemname}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="toolname" width="200"/>
      <el-table-column label="描述" align="center" prop="memo" />
      <el-table-column label="数据库类型" align="center" prop="dbtype">
        <template #default="scope">
          <dict-tag :options="operation_db_type" :value="scope.row.dbtype"/>
        </template>
      </el-table-column>
      <el-table-column label="sql内容" align="center" prop="sqlcontent" width="500">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            :content="scope.row.sqlcontent"
            placement="top"
          >
          <span
            class="multi-line"
          >{{scope.row.sqlcontent}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
<!--          <el-tag :type="isExecute(scope.row)?'success':'danger'">{{isExecute(scope.row)?"通过":"未通过"}}</el-tag>-->
          <el-tag v-if="scope.flowCode===null" type="success">通过</el-tag>
          <el-tag v-else-if="scope.flowCode!==null&&scope.row.status==='2'" type="success">通过</el-tag>
          <el-tag v-else-if="scope.flowCode!==null&&scope.row.status==='1'" type="primary">待审批</el-tag>
          <el-tag v-else type="danger">未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"
                     icon="SwitchButton"
                     @click="handleExecute(scope.row)"
                     v-hasPermi="['operation:sqltool:execute']"
                      :disabled="!isExecute(scope.row)">执行</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['operation:sqltool:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['operation:sqltool:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改sql执行工具对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="sqltoolRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="部门id" prop="deptid">
<!--          <el-input v-model="form.deptid" placeholder="请输入部门id" />-->
          <el-tree-select
            v-model="form.deptid"
            :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="请选择归属部门"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="系统" prop="busisystemid">
<!--          <el-input v-model="form.busisystemid" placeholder="请输入系统id" />-->
          <el-select
            v-model="form.busisystemid"
            placeholder="请选择系统"
          >
            <el-option
              v-for="item in systemList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @keyup.enter="handleQuery"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="toolname">
          <el-input v-model="form.toolname" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="memo">
          <el-input v-model="form.memo" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="数据库类型" prop="dbtype">
          <el-select v-model="form.dbtype"
                     placeholder="请选择数据库类型"
          >
            <el-option
              v-for="dict in operation_db_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              @click="getDBList(dict.label)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库url" prop="dburl">
<!--          <el-input v-model="form.dburl" placeholder="请输入数据库url" />-->
          <el-select
            v-model="form.dburl"
            :disabled="!form.dbtype"
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="请输入数据库url"
          >
            <el-option
              v-for="item in dbList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库用户" prop="dbusername">
          <el-input v-model="form.dbusername" placeholder="请输入数据库用户" />
        </el-form-item>
        <el-form-item label="数据库密码" prop="dbpassword">
          <el-input v-model="form.dbpassword" placeholder="请输入数据库密码" />
        </el-form-item>
        <el-form-item label="sql内容" prop="sqlcontent">
          <el-input v-model="form.sqlcontent" type="textarea" autosize placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="dialogTitle" v-model="resOpen" width="1500px" append-to-body>
      <div>
        <el-button
          plain
          icon="Download"
          style="float: right;margin-bottom: 20px"
          type="warning"
          @click="exportResult()">导出</el-button>
        <el-table :data="executeResTable">
          <el-table-column v-for="item in executeResHeader" :prop="item" :label="item"/>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Sqltool">
import {
  listSqltool,
  getSqltool,
  delSqltool,
  addSqltool,
  updateSqltool,
  executeSql,
  getSysList,
  getRmoteDBUrl,
} from "@/api/operation/sqltool";
import {deptTreeSelect} from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { operation_db_type } = proxy.useDict('operation_db_type');
const sqltoolList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const systemList = ref();

const dialogTitle = ref('');
// const title = ref("");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptid: undefined,
    busisystemid: undefined,
    toolname: undefined,
    memo: undefined,
    dbtype: undefined,
    sqlcontent: undefined,
    status: undefined,
  },
  rules: {
    deptid: [
      {required: true, message: "部门id不能为空", trigger: "blur"}
    ],
    busisystemid: [
      {required: true, message: "系统id不能为空", trigger: "blur"}
    ],
    toolname: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    memo: [
      {required: true, message: "描述不能为空", trigger: "blur"}
    ],
    dbtype: [
      {required: true, message: "数据库类型不能为空", trigger: "change"}
    ],
    dburl: [
      {required: true, message: "数据库url不能为空", trigger: "blur"}
    ],
    dbusername: [
      {required: true, message: "数据库用户不能为空", trigger: "blur"}
    ],
    dbpassword: [
      {required: true, message: "数据库密码不能为空", trigger: "blur"}
    ],
    sqlcontent: [
      {required: true, message: "sql内容不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "状态不能为空", trigger: "blur"}
    ],
  }
});

const dbList = ref([]);
const resOpen = ref(false)
const executeResHeader=ref([]);
const executeResTable=ref([]);
const deptOptions = ref(undefined);

const {queryParams, form, rules} = toRefs(data);

/**
 * 获得dbList
 */
function getDBList(dbType){
  console.log(dbType,"dbType")
  getRmoteDBUrl(dbType).then(res=>{
    dbList.value = res.data;
  })
}
/** 查询sql执行工具列表 */
function getList() {
  loading.value = true;
  listSqltool(queryParams.value).then(response => {
    sqltoolList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getBusiList(){
  getSysList().then(response => {
    systemList.value = response.rows;
    console.log(systemList,"====");
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptid: null,
    busisystemid: null,
    toolname: null,
    memo: null,
    dbtype: null,
    dburl: null,
    dbusername: null,
    dbpassword: null,
    sqlcontent: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("sqltoolRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加sql执行工具";
}
function isExecute(row){
  if(row.flowCode===null){
    return true
  }else{
    return row.status==='2'
  }
}
function handleExecute(row){
  console.log(row)
  dialogTitle.value = row.toolname
  executeSql(row.toolname).then(response => {
    resOpen.value = true
    //制作表头
    executeResHeader.value = response.data.tableHeader
    //制作表数据项
    executeResTable.value = response.data.tableData
  });
}
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    console.log(deptOptions.value)
  });
};
/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getSqltool(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改sql执行工具";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sqltoolRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateSqltool(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addSqltool(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}
function mouseenter(data){
  console.log(data)
}
function exportResult() {
  proxy.download('operation/sqltool/result/export', {
    toolname: dialogTitle.value
  }, `${dialogTitle.value}_${new Date().getTime()}.xlsx`)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除sql执行工具编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delSqltool(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('operation/sqltool/export', {
    ...queryParams.value
  }, `sqltool_${new Date().getTime()}.xlsx`)
}
getBusiList();
getDeptTree();
getList();
</script>

<style>
.multi-line {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
}
.tooltip-base-box .box-item {
  width: 410px;
  margin-top: 10px;
}
.el-popper.is-dark{
  //width: auto;
}
</style>
